﻿namespace PayPal.AdaptivePayments
{
    using System.Web.WebPages.Scope;
    using PayPal.Platform.SDK;

    public static class RefundPartialPayment
    {
        public static RefundResponse Execute(Receiver[] receivers, string payKey, string trackingId, string currencyCode = "", string language = "")
        {
            if (string.IsNullOrEmpty(currencyCode))
            {
                currencyCode = Profile.CurrencyCode;
            }

            if (string.IsNullOrEmpty(language))
            {
                language = Profile.Language;
            }

            Validate(receivers, payKey, trackingId, language, currencyCode);

            RefundRequest refundRequest = new RefundRequest();

            // payKey gets first preference
            if (!string.IsNullOrEmpty(payKey))
            {
                refundRequest.payKey = payKey;
            }
            else if (!string.IsNullOrEmpty(trackingId))
            {
                refundRequest.trackingId = trackingId;
            }

            refundRequest.receiverList = receivers;
            refundRequest.currencyCode = currencyCode;

            refundRequest.requestEnvelope = new RequestEnvelope();
            refundRequest.requestEnvelope.errorLanguage = language;

            AdapativePayments ap = new AdapativePayments();
            ap.APIProfile = Profile.FNProfile;
            RefundResponse response = ap.Refund(refundRequest);

            if (ap.LastError != null)
            {
                throw ap.LastError;
            }

            return response;
        }

        private static void Validate(Receiver[] receivers, string payKey, string trackingId, string language, string currencyCode)
        {
            ValidationHelper.ValidateProfile(Profile.FNProfile);
            ValidationHelper.ValidateLanguage(language);
            ValidationHelper.ValidateCurrencyCode(currencyCode);
        }
    }
}

